package com.libinshen.wxpay.videoAliBaBa.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.libinshen.wxpay.videoAliBaBa.entity.Chapter;
import com.libinshen.wxpay.videoAliBaBa.entity.Video;
import com.libinshen.wxpay.videoAliBaBa.entity.vo.ChapterVo;
import com.libinshen.wxpay.videoAliBaBa.entity.vo.VideoVo;
import com.libinshen.wxpay.videoAliBaBa.mapper.ChapterMapper;
import com.libinshen.wxpay.videoAliBaBa.service.ChapterService;
import com.libinshen.wxpay.videoAliBaBa.service.VideoService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lbs
 */
@Service
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapter> implements ChapterService {

    @Resource
    private VideoService videoService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeChapterById(String id) {
        //TODO 此处调用vod 中的删除视频文件的接口

        //删除章节。先删除视频叶子节点
        videoService.getCountByChapterId(id);
        Integer result = baseMapper.deleteById(id);
        return null != result && result > 0;
    }

    @Override
    public List<ChapterVo> nestedList(String courseId) {
        //最终要的到的数据列表
        ArrayList<ChapterVo> chapterVoArrayList = new ArrayList<>();

        //获取章节列表信息：List<ChapterVo>
        QueryWrapper<Chapter> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("course_id", courseId);
        queryWrapper1.orderByAsc("sort", "id");
        List<Chapter> chapterList = baseMapper.selectList(queryWrapper1);

        //获取课时信息
        QueryWrapper<Video> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("course_id", courseId);
        queryWrapper2.orderByAsc("sort", "id");
        List<Video> videoList = videoService.list(queryWrapper2);
        //将videoList转换为Map

        for (int i = 0; i < chapterList.size(); i++) {
            Chapter chapter = chapterList.get(i);
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(chapterVo, chapter);
            chapterVoArrayList.add(chapterVo);

            List<VideoVo> videoVoList = new ArrayList<>();
            for (int j = 0; j < videoList.size(); j++) {
                Video video = videoList.get(i);
                if (chapter.getId().equals(video.getChapterId())) {
                    VideoVo videoVo = new VideoVo();
                    BeanUtils.copyProperties(video, videoVo);
                    videoVoList.add(videoVo);
                }
                chapterVo.setChildren(videoVoList);
            }
        }

        return chapterVoArrayList;
    }
}
